package cn.zhang.reimbursement_1.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.zhang.reimbursement_1.common.GetKeyValue;
import cn.zhang.reimbursement_1.config.LoginInterceptor;
import cn.zhang.reimbursement_1.mapper.ClassOnMapper;
import cn.zhang.reimbursement_1.mapper.RecordMapper;
import cn.zhang.reimbursement_1.mapper.UserMapper;
import cn.zhang.reimbursement_1.model.ClassOn;
import cn.zhang.reimbursement_1.model.Record;
import cn.zhang.reimbursement_1.model.User;
import cn.zhang.reimbursement_1.request.LoginRequest;
import cn.zhang.reimbursement_1.tools.CommonUtil;
import cn.zhang.reimbursement_1.tools.JsonData;
import cn.zhang.reimbursement_1.vo.ReimburseVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhang.reimbursement_1.model.Reimburse;
import cn.zhang.reimbursement_1.service.ReimburseService;
import cn.zhang.reimbursement_1.mapper.ReimburseMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author zfs90
* @description 针对表【t_reimburse】的数据库操作Service实现
* @createDate 2022-03-26 16:33:23
*/
@Service
public class ReimburseServiceImpl implements ReimburseService{

    @Autowired
    private ReimburseMapper reimburseMapper;

    @Autowired
    private ClassOnMapper classOnMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RecordMapper recordMapper;

    /**
     * 添加
     * @param reimburse
     * @return
     */
    @Override
    public JsonData saveReimburse(Reimburse reimburse) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (reimburse==null){
            return JsonData.buildCodeAndMsg(-1,"添加申请记录不可为空");
        }
        //获取用户记录
        User user = userMapper.selectById(loginRequest.getId());
        //获取部门
        ClassOn classOn = classOnMapper.selectOne(new QueryWrapper<ClassOn>()
                .lambda().eq(ClassOn::getClassOn,user.getClassNo()));
        //获取经理的user记录
        User managerUser = userMapper.selectOne(new QueryWrapper<User>()
                .lambda().eq(User::getTruename,classOn.getManager()));


        Reimburse saveReimburse = new Reimburse();
        BeanUtils.copyProperties(reimburse,saveReimburse);
        saveReimburse.setCreateTime(new Date());
        saveReimburse.setSqUserid(loginRequest.getId());
        saveReimburse.setSpUserid(managerUser.getId());
        saveReimburse.setClassNo(classOn.getClassOn());
        saveReimburse.setStatus(3);
        saveReimburse.setCaiwuState(3);

        reimburseMapper.insert(saveReimburse);

        return JsonData.buildSuccess();
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param like
     * @return
     */
    @Override
    public JsonData pageGetReimburse(int pageNum, int pageSize, String like) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        User user = userMapper.selectById(loginRequest.getId());
        Page<Reimburse> reimbursePage = new Page<>();
        if (loginRequest.getRolename().equals("经理")){
            reimbursePage = reimburseMapper.selectPage(new Page<>(pageNum,pageSize)
                    , Wrappers.<Reimburse>lambdaQuery()
                            .like(Reimburse::getStatus,like)
                            .eq(Reimburse::getClassNo,user.getClassNo())
                            .orderByDesc(Reimburse::getCreateTime));
        }else if (loginRequest.getRolename().equals("员工")){
            reimbursePage = reimburseMapper.selectPage(new Page<>(pageNum,pageSize)
                    , Wrappers.<Reimburse>lambdaQuery()
                            .like(Reimburse::getStatus,like)
                            .eq(Reimburse::getSqUserid,user.getId())
                            .orderByDesc(Reimburse::getCreateTime));
        }else if (loginRequest.getRolename().equals("财务")){
            reimbursePage = reimburseMapper.selectPage(new Page<>(pageNum,pageSize)
                    , Wrappers.<Reimburse>lambdaQuery()
                            .like(Reimburse::getStatus,like)
                            .eq(Reimburse::getStatus,1)
                            .orderByDesc(Reimburse::getCreateTime));
        }
        Map<String,Object> map = new HashMap<>(3);
        map.put("total_pages",reimbursePage.getPages());
        map.put("total_record",reimbursePage.getTotal());
        map.put("records_data",reimbursePage.getRecords().stream().map(obj->{
            ReimburseVO reimburseVO = new ReimburseVO();
            BeanUtils.copyProperties(obj,reimburseVO);
            return reimburseVO;
        }).collect(Collectors.toList()));

        return JsonData.buildSuccess(map);
    }

    /**
     * 通过审批
     * @return
     */
    @Override
    public JsonData passReimburse(long id) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (id==0){
            return JsonData.buildCodeAndMsg(-1,"审批对象不可为空");
        }

        Reimburse reimburse1 = reimburseMapper.selectById(id);
        if (loginRequest.getRolename().equals("经理")){
            if (reimburse1.getStatus()==3){
                reimburse1.setStatus(1);
                reimburseMapper.updateById(reimburse1);
            }else if (reimburse1.getStatus()==1){
                return JsonData.buildCodeAndMsg(-1,"申请已处理，请勿重复操作");
            }
        }else if (loginRequest.getRolename().equals("财务")){
            if (reimburse1.getStatus()==1 && reimburse1.getCaiwuState()==1 || reimburse1.getCaiwuState()==2){
                return JsonData.buildCodeAndMsg(-1,"申请已处理，请勿重复操作");
            }
            if (reimburse1.getStatus()==1 && reimburse1.getCaiwuState()==3){
                reimburse1.setCaiwuState(1);
                reimburseMapper.updateById(reimburse1);
            }else {
                return JsonData.buildCodeAndMsg(-1,"经理未通过，请勿操作");
            }
            
        }



        User user = userMapper.selectById(reimburse1.getSqUserid());

        Record record = new Record();
        record.setRealname(loginRequest.getUsername());
        record.setOperation("通过");
        record.setInsertTime(new Date());
        record.setDetails("通过了"+user.getTruename()+"的申请");

        recordMapper.insert(record);


        return JsonData.buildSuccess();
    }

    /**
     * 未通过审核
     * @return
     */
    @Override
    public JsonData unPassReimburse(long id ,String reason) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (id==0||StringUtils.isBlank(reason)){
            return JsonData.buildCodeAndMsg(-1,"审批对象不可为空");
        }
        Reimburse reimburse1 = reimburseMapper.selectById(id);
        if (loginRequest.getRolename().equals("经理")){
            if (reimburse1.getStatus()==3){
                reimburse1.setStatus(2);
                reimburseMapper.updateById(reimburse1);
            }else if (reimburse1.getStatus()==2){
                return JsonData.buildCodeAndMsg(-1,"申请已处理，请勿重复操作");
            }else if (reimburse1.getStatus()==1){
                return JsonData.buildCodeAndMsg(-1,"申请已处理，请勿重复操作");
            }
        }else if (loginRequest.getRolename().equals("财务")){
            if (reimburse1.getStatus()==1 && reimburse1.getCaiwuState()==2|| reimburse1.getCaiwuState()==1){
                return JsonData.buildCodeAndMsg(-1,"申请已处理，请勿重复操作");
            }
            if (reimburse1.getStatus()==1 && reimburse1.getCaiwuState()==3){
                reimburse1.setCaiwuState(2);
                reimburseMapper.updateById(reimburse1);
            }
            else {
                return JsonData.buildCodeAndMsg(-1,"经理未通过，请勿操作");
            }

        }


        User user = userMapper.selectById(reimburse1.getSqUserid());

        Record record = new Record();
        record.setRealname(loginRequest.getUsername());
        record.setOperation("拒绝");
        record.setInsertTime(new Date());
        record.setDetails("拒绝"+user.getTruename()+"的申请");
        recordMapper.insert(record);

        return JsonData.buildSuccess();
    }

    /**
     * 查询两个日期出差次数
     * 1 确定开始时间和结束时间
     * 2 根据开始时间和结束时间  查询有出差记录的员工
     * 3 根据查出的员工id列表   和之前的开始时间结束时间一起查询出  在时间内每一个员工的出差次数；
     *
     * （1） 时间怎么确定的？
     *       （1 根据前端传来的时间进行确定
     *       （2 创建默认时间
     * （2） 怎么查出每个员工的名字？
     *
     * （3） 以什么形式进行返回给前端？
     *             key：value
     * @param start
     * @param end
     * @return
     */
    @Override
    public JsonData getTwoTimeCount(String start, String end) throws ParseException {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        User user1 = userMapper.selectById(loginRequest.getId());
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String defaultStartTime = CommonUtil.getDayByTow(15);
        Date endOfDayData = DateUtil.endOfDay(new Date());

        String endOfDay = DateUtil.format(endOfDayData, "yyyy-MM-dd HH:mm:ss");
        Date date = DateUtil.parse(end);
        end = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");


        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isBlank(start)||StringUtils.isBlank(end)){
            ids =  reimburseMapper.getAllSqidsByDay(defaultStartTime,endOfDay,user1.getClassNo());
        }else {
            ids =  reimburseMapper.getAllSqidsByDay(start,end,user1.getClassNo());
        }

        //确定员工的名字
        List<User> userList = ids.stream().map(obj -> {
            User user = userMapper.selectById(obj);
            return user;
        }).collect(Collectors.toList());

        List<GetKeyValue> getKeyValues = new ArrayList<>();
        if (loginRequest.getRolename().equals("经理")){
            //以key:value 形式返还
            for (int i = 0; i < userList.size(); i++) {
                GetKeyValue item = new GetKeyValue();
                User user = userList.get(i);
                Integer count = 0;
                if (StringUtils.isBlank(start)||StringUtils.isBlank(end)){
                    count  = reimburseMapper.getTwoCountBySqUserId(defaultStartTime,endOfDay,user.getId(),user1.getClassNo());
                }else {
                    count = reimburseMapper.getTwoCountBySqUserId(start,end,user.getId(),user1.getClassNo());
                }
                if (count==null){
                    count =  0;
                }
                item.setKey(user.getTruename());
                item.setValue(count);
                getKeyValues.add(item);
            }
        }



        return JsonData.buildSuccess(getKeyValues);
    }

    /**
     * 员工确认
     * @param id
     * @return
     */
    @Override
    public JsonData confirm(long id) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (id==0){
            return JsonData.buildCodeAndMsg(-1,"确认审批不可为空");
        }
        Reimburse reimburse = reimburseMapper.selectById(id);
        String num = CommonUtil.getStringNumRandom(16);
        if (loginRequest.getRolename().equals("员工")){
            if (reimburse.getStatus()==1 && reimburse.getCaiwuState()==1){
                if(StringUtils.isBlank(reimburse.getReNum())){
                    reimburse.setReNum(num);
                    reimburseMapper.updateById(reimburse);
                }else {
                    return JsonData.buildCodeAndMsg(-1,"请勿重复确认！");
                }
            }else {
                return JsonData.buildCodeAndMsg(-1,"必须经理和财务都通过才可确认！");
            }
        }else {
            return JsonData.buildCodeAndMsg(-1,"无法确认！");
        }
        return JsonData.buildSuccess();
    }
}




